import 'package:OASys/api/MeetingApi.dart';
import 'package:OASys/api/UserApi.dart';
import 'package:OASys/components/FormComponents.dart';
import 'package:OASys/components/scaffoldItem.dart';
import 'package:OASys/entity/MeetingInfoVo.dart';
import 'package:OASys/entity/UserVo.dart';
import 'package:flutter/material.dart';

class MeetingEditPage extends StatelessWidget {
  final Map arguments;

  MeetingEditPage({this.arguments, Key key});
  @override
  Widget build(BuildContext context) {
    return ScaffoldItem(
        '编辑会议信息',
        MyMeetingEditPage(
          meetingId: arguments == null ? -1 : arguments['id'],
        ));
  }
}

class MyMeetingEditPage extends StatefulWidget {
  final int meetingId;

  MyMeetingEditPage({this.meetingId = -1, Key key});

  @override
  _MyMeetingEditPageState createState() => _MyMeetingEditPageState();
}

class _MyMeetingEditPageState extends State<MyMeetingEditPage> {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();

  MeetingInfoVo meetingInfoVo;
  MeetingInfoVo info;
  List<Map<String, dynamic>> parentList = [];
  List<Map<String, dynamic>> selectList = [];
  List<UserVo> userList = [];
  List<int> ids = [];
  List<UserVo> participantList = [];
  List<Map<String, dynamic>> typeList = [];

  DateTime meetingDay;
  TimeOfDay beginTime;
  TimeOfDay overTime;
  @override
  void initState() {
    super.initState();
    getUserList();
    buildStatusList();
    if (widget.meetingId == -1) {
      setState(() {
        info = new MeetingInfoVo();
        meetingInfoVo = new MeetingInfoVo();
        print(info.participantList);
      });
    } else {
      getMeetingInfo(widget.meetingId);
    }
  }

  void buildStatusList() {
    setState(() {
      typeList.add({"key": 0, "value": "项目会议"});
      typeList.add({"key": 1, "value": "日常例会"});
      typeList.add({"key": 2, "value": "培训会议"});
      typeList.add({"key": 3, "value": "月度汇报会议"});
      typeList.add({"key": 4, "value": "季度汇报会议"});
      typeList.add({"key": 5, "value": "年度汇报会议"});
    });
  }

  void getUserList() {
    UserApi().list(1, 1000, success: (res) {
      setState(() {
        userList = res;
      });
    }, error: (err) {
      print(err.code);
      showFailMessage(context);
    });
  }

  void getMeetingInfo(int id) {
    MeetingApi().info(
      id,
      success: (res) {
        setState(() {
          meetingInfoVo = MeetingInfoVo.fromJson(res.toJson());
          info = res;
          meetingDay = DateTime.parse(info.beginTime);
          beginTime = TimeOfDay.fromDateTime(DateTime.parse(info.beginTime));
          overTime = TimeOfDay.fromDateTime(DateTime.parse(info.overTime));
        });
        print(res.toJson().toString());
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  //保存操作
  void save() {
    var form = formKey.currentState;
    String begin = bulidDayStr(meetingDay) + " " + bulidTimeStr(beginTime);
    String over = bulidDayStr(meetingDay) + " " + bulidTimeStr(overTime);
    if (form.validate()) {
      form.save();
      if (DateTime.parse(begin).isAfter(DateTime.now())) {
        if (DateTime.parse(begin).isBefore(DateTime.parse(over))) {
          setState(() {
            info.beginTime = begin;
            info.overTime = over;
            print(info.toJson());
            doSave();
          });
        } else {
          showMessage(context, "会议开始时间不得提前于结束时间");
        }
      } else {
        showMessage(context, "会议日期不得提前于当前日期");
      }
    }
  }

  // 发起保存请求
  void doSave() {
    MeetingApi().save(
      info,
      success: (res) {
        showSuccessMessage(context);
        Navigator.of(context).pop(true);
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  // 构建所有用户列表
  void bulidParentList(List<UserVo> list) {
    setState(() {
      parentList = [];
      list.forEach((element) {
        parentList.add({"key": element.id, "value": element.nickname});
      });
    });
  }

  // 构建选中用户列表
  void bulidSelectList(List<UserVo> list) {
    setState(() {
      selectList = [];
      if (list != null) {
        list.forEach((element) {
          selectList.add({"key": element.id, "value": element.nickname});
        });
      }
    });
  }

  // 根据ids更新参与用户列表
  void bulidParticipantList() {
    print(ids.toString());
    setState(() {
      if (ids != null && ids.length > 0) {
        participantList = [];
        userList.forEach((element) {
          if (ids.indexOf(element.id) >= 0) {
            participantList.add(element);
          }
        });
        info.participantList = participantList;
      }
    });
  }

  // 重置表单
  void reset() {
    var form = formKey.currentState;
    form.reset();
    setState(() {
      info.type = int.parse(meetingInfoVo.type.toString());
      info.typeName = meetingInfoVo.typeName;
      info.participantList = meetingInfoVo.participantList;
      meetingDay = DateTime.parse(info.beginTime);
      beginTime = TimeOfDay.fromDateTime(DateTime.parse(info.beginTime));
      overTime = TimeOfDay.fromDateTime(DateTime.parse(info.overTime));
    });
  }

  // 单选框
  selectOne() {
    showOneSelect(context, info.type);
  }

  // 多选框
  selectMultiple() {
    bulidParentList(userList);
    bulidSelectList(info.participantList);
    showMulSelect(context, parentList: parentList, selectList: selectList);
  }

  // 构建时间字符串 用于显示
  String bulidTimeStr(TimeOfDay time) {
    String hour =
        time.hour < 10 ? "0" + time.hour.toString() : time.hour.toString();
    String minute = time.minute < 10
        ? "0" + time.minute.toString()
        : time.minute.toString();
    return hour + ":" + minute + ":00";
  }

  // 构建日期字符串 用于显示
  String bulidDayStr(DateTime dateTime) {
    return dateTime.toString().substring(0, 10);
  }

  // 构建表单参与列表
  Widget buildUserItem(int index) {
    return Container(
      width: 150,
      height: 20,
      alignment: Alignment.center,
      child: Text(info.participantList[index].nickname),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (info == null || meetingInfoVo == null) {
      return Container(
        child: Text('加载中'),
      );
    } else {
      return SingleChildScrollView(
        child: Container(
          width: 500,
          margin: EdgeInsets.all(10),
          child: Card(
            child: Container(
              margin: EdgeInsets.all(10),
              child: Form(
                key: formKey,
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('会议名称：'),
                        FormInput(
                          initValue: meetingInfoVo.name,
                          hintText: "请输入会议名",
                          validator: (content) {
                            if (content.length > 12) {
                              return "会议名过长";
                            } else if (content.length <= 0) {
                              return "会议名过短";
                            }
                          },
                          onSave: (value) {
                            info.name = value;
                          },
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('会议地点：'),
                        FormInput(
                          initValue: meetingInfoVo.place,
                          hintText: "请输入会议地点",
                          validator: (content) {
                            if (content.length > 12) {
                              return "地点过长";
                            } else if (content.length <= 0) {
                              return "地点过短";
                            }
                          },
                          onSave: (value) {
                            info.place = value;
                          },
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('会议类型：'),
                        Container(
                          width: 200,
                          height: 50,
                          alignment: Alignment.centerLeft,
                          child: FlatButton(
                            minWidth: 200,
                            onPressed: () {
                              selectOne();
                            },
                            child: Container(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                info.type == null ? "请选择会议类型" : info.typeName,
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  letterSpacing: 1,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('会议主题：'),
                        FormText(
                          initValue: meetingInfoVo.topic,
                          hintText: "请输入会议主题",
                          validator: (content) {
                            if (content.length <= 0) {
                              return "会议主题过短";
                            }
                          },
                          onSave: (value) {
                            info.topic = value;
                          },
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('会议简要：'),
                        FormText(
                          initValue: meetingInfoVo.description,
                          hintText: "请输入会议简要",
                          validator: (content) {
                            if (content.length <= 0) {
                              return "会议简要过短";
                            }
                          },
                          onSave: (value) {
                            info.description = value;
                          },
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('会议日期：'),
                        Container(
                          width: 200,
                          height: 50,
                          alignment: Alignment.centerLeft,
                          child: FlatButton(
                            minWidth: 200,
                            onPressed: () async {
                              DateTime result = await showDatePicker(
                                context: context,
                                initialDate: meetingDay == null
                                    ? DateTime.now()
                                    : meetingDay,
                                firstDate: DateTime(DateTime.now().year),
                                lastDate: DateTime(2035),
                                helpText: "选择会议日期",
                                cancelText: "取消",
                                confirmText: "保存",
                              );
                              if (result != null) {
                                setState(() {
                                  meetingDay = result;
                                });
                              }
                            },
                            child: Container(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                meetingDay == null
                                    ? "请选择会议日期"
                                    : meetingDay.toString().substring(0, 10),
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  letterSpacing: 1,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('开始时间：'),
                        Container(
                          width: 200,
                          height: 50,
                          alignment: Alignment.centerLeft,
                          child: FlatButton(
                            minWidth: 200,
                            onPressed: () async {
                              var result = await showTimePicker(
                                context: context,
                                initialTime: TimeOfDay.now(),
                                builder: (BuildContext context, Widget child) {
                                  return MediaQuery(
                                    data: MediaQuery.of(context)
                                        .copyWith(alwaysUse24HourFormat: true),
                                    child: child,
                                  );
                                },
                                helpText: "选择开始时间",
                                cancelText: "取消",
                                confirmText: "保存",
                              );
                              if (result != null) {
                                setState(() {
                                  beginTime = result;
                                });
                              }
                            },
                            child: Container(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                beginTime == null
                                    ? "请选择开始时间"
                                    : bulidTimeStr(beginTime),
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  letterSpacing: 1,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('结束时间：'),
                        Container(
                          width: 200,
                          height: 50,
                          alignment: Alignment.centerLeft,
                          child: FlatButton(
                            minWidth: 200,
                            onPressed: () async {
                              var result = await showTimePicker(
                                context: context,
                                initialTime: overTime == null
                                    ? TimeOfDay.now()
                                    : overTime,
                                builder: (BuildContext context, Widget child) {
                                  return MediaQuery(
                                    data: MediaQuery.of(context)
                                        .copyWith(alwaysUse24HourFormat: true),
                                    child: child,
                                  );
                                },
                                helpText: "选择结束时间",
                                cancelText: "取消",
                                confirmText: "保存",
                              );
                              if (result != null) {
                                setState(() {
                                  overTime = result;
                                });
                              }
                            },
                            child: Container(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                overTime == null
                                    ? "请选择结束时间"
                                    : bulidTimeStr(overTime),
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  letterSpacing: 1,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('会议参与者：'),
                        Container(
                          width: 200,
                          height: 150,
                          alignment: Alignment.center,
                          child: FlatButton(
                            onPressed: () {
                              selectMultiple();
                            },
                            child: ListView.builder(
                              itemCount: info.participantList == null
                                  ? 0
                                  : info.participantList.length,
                              itemBuilder: (BuildContext context, int index) {
                                return buildUserItem(index);
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        RaisedButton(
                          color: Color.fromRGBO(33, 150, 243, 1),
                          onPressed: save,
                          child: Text(
                            "保 存",
                            style: TextStyle(color: Colors.white),
                          ),
                        ),
                        RaisedButton(
                          color: Color.fromRGBO(103, 194, 58, 1),
                          onPressed: reset,
                          child: Text(
                            "重 置",
                            style: TextStyle(color: Colors.white),
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      );
    }
  }

  // 显示单选
  showOneSelect(BuildContext context, int oldType) {
    int type = oldType;
    String typeName;

    Widget bulidListItem(int index, StateSetter setState) {
      return Row(
        children: [
          Flexible(
            child: RadioListTile(
              title: Text(typeList[index]["value"]),
              value: index,
              groupValue: type,
              onChanged: (value) {
                setState(() {
                  type = value;
                  typeName = typeList[index]["value"];
                  info.type = value;
                  info.typeName = typeList[index]["value"];
                });
              },
            ),
          ),
        ],
      );
    }

    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            titlePadding: EdgeInsets.all(0),
            title: Container(
              height: 50,
              alignment: Alignment.center,
              child: Text(
                '会议类型选择',
                style: TextStyle(color: Colors.white),
              ),
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(3),
                  topRight: Radius.circular(3),
                ),
              ),
            ),
            contentPadding: EdgeInsets.all(0),
            content: new StatefulBuilder(
              builder: (context, StateSetter setState) {
                return Container(
                  height: 300,
                  width: 300,
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(250, 250, 250, 1),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Column(
                    children: [
                      Container(
                        margin: EdgeInsets.only(
                          top: 20,
                          bottom: 20,
                        ),
                        height: 260,
                        width: 200,
                        child: ListView.builder(
                            itemCount: typeList.length,
                            itemBuilder: (context, index) {
                              return bulidListItem(index, setState);
                            }),
                      ),
                    ],
                  ),
                );
              },
            ),
            actions: <Widget>[
              RaisedButton(
                color: Color.fromRGBO(33, 150, 243, 1),
                child: Text("保 存"),
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
              ),
            ],
          );
        }).then((value) {
      print(value);
      if (value != null && value) {
        setState(() {
          info.type = type;
          info.typeName = typeName;
        });
      }
    });
  }

  // 显示多选
  showMulSelect(
    BuildContext context, {
    List<Map<String, dynamic>> parentList,
    List<Map<String, dynamic>> selectList,
  }) async {
    if (parentList == null) {
      parentList = [];
    }
    if (selectList == null) {
      selectList = [];
    }
    List<bool> boolList = buildBoolList("key", selectList, parentList);
    Widget bulidListItem(
        BuildContext context, int index, StateSetter setState) {
      return CheckboxListTile(
        title: new Text(parentList[index]["value"].toString()),
        value: boolList[index],
        onChanged: (bool flag) {
          setState(() {
            boolList[index] = flag;
          });
        },
      );
    }

    List<int> buildIntList() {
      List<int> intList = [];
      for (int index = 0; index < boolList.length; index++) {
        if (boolList[index]) {
          intList.add(parentList[index]["key"]);
        }
      }
      return intList;
    }

    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            titlePadding: EdgeInsets.all(0),
            title: Container(
              height: 50,
              alignment: Alignment.center,
              child: Text(
                '会议参与者选择',
                style: TextStyle(color: Colors.white),
              ),
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(3),
                  topRight: Radius.circular(3),
                ),
              ),
            ),
            contentPadding: EdgeInsets.all(0),
            content: new StatefulBuilder(
              builder: (context, StateSetter setState) {
                return Container(
                  height: 300,
                  width: 300,
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(250, 250, 250, 1),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Container(
                    margin: EdgeInsets.only(
                      top: 20,
                      bottom: 20,
                    ),
                    height: 260,
                    child: ListView.builder(
                        itemCount: parentList.length,
                        itemBuilder: (
                          context,
                          index,
                        ) {
                          return bulidListItem(context, index, setState);
                        }),
                  ),
                );
              },
            ),
            actions: <Widget>[
              RaisedButton(
                color: Color.fromRGBO(33, 150, 243, 1),
                child: Text("保 存"),
                onPressed: () {
                  Navigator.of(context).pop(buildIntList());
                },
              ),
              RaisedButton(
                color: Color.fromRGBO(245, 108, 108, 1),
                child: Text('重 置'),
                onPressed: () {
                  print('重 置');
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        }).then((value) {
      setState(() {
        ids = value;
        bulidParticipantList();
      });
    });
  }
}
